import CryptoJS from 'crypto-js';

// 讯飞开放平台的配置信息
const appId = '72be4bef';
const apiKey = 'b67d9f8f7deac5f606a85150f985cee6';
const apiSecret = 'NmJiNzdkZGQxNzg0NGNjM2EyNDM5NjRj';
const host = 'tts-api.xfyun.cn';
const path = '/v2/tts';

// 语音合成的业务参数
const business = {
    aue: 'raw', // 音频编码格式
    vcn: 'xiaoyan', // 发音人
    pitch: 50,
    speed: 50
};

let socket = null; // WebSocket实例
let connectionPromise = null; // 连接Promise，用于跟踪连接状态
let isConnecting = false; // 连接中标志
let isConnected = false; // 已连接标志

// 生成签名
function generateSignature() {
    const date = new Date().toUTCString();
    const signatureOrigin = `host: ${host}\ndate: ${date}\nGET ${path} HTTP/1.1`;
    const hash = CryptoJS.HmacSHA256(signatureOrigin, apiSecret);
    const signature = btoa(hash.toString(CryptoJS.enc.Base64));
    const authorizationOrigin = `api_key="${apiKey}",algorithm="hmac-sha256",headers="host date request-line",signature="${signature}"`;
    return btoa(authorizationOrigin);
}

// 初始化WebSocket连接
async function initWebSocket() {
    // 如果已有连接Promise，直接返回
    if (connectionPromise) {
        return connectionPromise;
    }
    
    // 防止重复连接
    if (isConnecting) {
        return connectionPromise;
    }
    
    isConnecting = true;
    
    connectionPromise = new Promise((resolve, reject) => {
        const authorization = generateSignature();
        const date = new Date().toUTCString();
        const url = `wss://${host}${path}?authorization=${authorization}&date=${date}&host=${host}`;
        
        socket = uni.connectSocket({
            url: url,
            success: (res) => {
                console.log('WebSocket连接成功', res);
            },
            fail: (err) => {
                console.error('WebSocket连接失败', err);
                isConnecting = false;
                isConnected = false;
                connectionPromise = null;
                reject(err);
            }
        });
        
        // 监听WebSocket事件
        socket.onOpen(() => {
            console.log('WebSocket连接已打开');
            isConnecting = false;
            isConnected = true;
            resolve(socket);
        });
        
        socket.onMessage((event) => {
            try {
                const response = JSON.parse(event.data);
                console.log('收到消息:', response);
                
                if (response.code !== 0) {
                    console.error('服务器返回错误:', response);
                    return;
                }
                
                if (response.data) {
                    if (response.data.status === 2) {
                        // 合成结束
                        console.log('合成完成');
                        const audioData = atob(response.data.audio);
                        resolve({ code: 0, data: audioData });
                        
                        // 可以选择在这里关闭连接
                        // closeWebSocket();
                    }
                }
            } catch (error) {
                console.error('解析响应数据错误', error);
                reject(error);
            }
        });
        
        socket.onClose(() => {
            console.log('WebSocket连接已关闭');
            isConnecting = false;
            isConnected = false;
            connectionPromise = null;
            socket = null;
            reject(new Error('WebSocket连接已关闭'));
        });
        
        socket.onError((err) => {
            console.error('WebSocket连接错误', err);
            isConnecting = false;
            isConnected = false;
            connectionPromise = null;
            socket = null;
            reject(err);
        });
    });
    
    return connectionPromise;
}

// 发送文字合成请求
async function sendTextToSpeech(text) {
    try {
        // 确保WebSocket已连接
        if (!isConnected) {
            await initWebSocket();
        }
        
        const common = {
            app_id: appId
        };
        const data = {
            status: 2,
            text: btoa(text) // 对文本进行base64编码
        };
        const request = {
            common: common,
            business: business,
            data: data
        };
        
        return new Promise((resolve, reject) => {
            socket.send({
                data: JSON.stringify(request),
                success: (sendRes) => {
                    console.log('数据发送成功', sendRes);
                    
                    // 等待消息处理完成
                    connectionPromise.then(result => {
                        resolve(result);
                    }).catch(err => {
                        reject(err);
                    });
                },
                fail: (sendErr) => {
                    console.error('数据发送失败', sendErr);
                    reject(sendErr);
                }
            });
        });
    } catch (error) {
        console.error('发送语音合成请求失败', error);
        throw error;
    }
}

export async function xunfeiInit(text) {
    try {
        return await sendTextToSpeech(text);
    } catch (error) {
        return { code: -1, message: error.message };
    }
}

export function closeWebSocket() {
    if (socket) {
        socket.close({
            success: () => {
                console.log('WebSocket连接关闭成功');
                isConnected = false;
                connectionPromise = null;
                socket = null;
            },
            fail: (err) => {
                console.error('WebSocket连接关闭失败', err);
            }
        });
    }
}